import { RouteBaseImpl } from "./RouteBaseImpl";
import { RouteConfig } from "./RouteConfig";

export class RouteUniImpl extends RouteBaseImpl {

	navigateTo(option) {
		super.navigateTo(option)

		option.parameter = option.parameter || {}
		option.success = function(res) {
			// 路由传参存在第二次获取不到BUG(uniapp vue3 H5环境下)
			// 以下代码作为临时解决方案
			console.log( res)
			console.log( option.parameter)
			let pages =  getCurrentPages()
			console.log(pages)
			// if(option.url == ("/" + pages[pages.length-1].route)){
				
			// 	console.log(option.url)
			// 	if(pages[pages.length-1].routeParameterEvent)
			// 		pages[pages.length-1].routeParameterEvent(option.parameter)
			// }else{
				
				console.log(res.eventChannel.id)
				res.eventChannel.emit(res.eventChannel.id, option.parameter)
			// }
		}
		uni.navigateTo(option);
	}
	reLaunchTo(option) {
		super.reLaunchTo(option)

		option.parameter = option.parameter || {}
		option.success = function(res) {
			res.eventChannel.emit(res.eventChannel.id, option.parameter)
		}

		uni.reLaunch(option);
	}
	goBack(option) {
		super.goBack(option)

		uni.navigateBack(option);
	}
}

export var uniRouteMixin = {
	data() {
		return {
			routeParameter: undefined,
			eventChannel: undefined
		}
	},
	onLoad: function(option) {
		// #ifdef APP-NVUE
		const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
		// #endif
		// #ifndef APP-NVUE
		const eventChannel = this.getOpenerEventChannel();
		// #endif
		this.eventChannel = eventChannel
		// // 监听routeParameterEvent事件，获取上一页面通过eventChannel传送到当前页面的数据
		eventChannel.on(eventChannel.id, this.routeParameterEvent)
	},
	methods: {
		routeParameterEvent(data) {
			 console.log(data)
			this.routeParameter = data
		},
		sendRouteParameter(pageName,id,data) {
			let pages =  getCurrentPages()
			const configPage = RouteConfig.pages[pageName]
			for(const page of pages){
				if(page.route == configPage.path){
					console.log(page)
					// #ifdef MP-WEIXIN
					
					page.$vm.fromRouteParameterEvent(id,data)
					// #endif
					// #ifndef MP-WEIXIN
					
					page.fromRouteParameterEvent(id,data)
					// #endif
					break
				}
			}
			
		}
	}
}